<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\ChannelGroupRequest;
use App\Http\Requests\ChannelProductRequest;
use App\Http\Requests\CzChannelRequest;
use App\Models\ChannelGroup;
use App\Models\ChannelGroupItem;
use App\Models\ChannelMoneyLog;
use App\Models\ChannelOrder;
use App\Models\ChannelProduct;
use App\Models\CzChannel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CzChannelController extends ApiBaseController
{
    public function changeMoney(Request $request)
    {
        $type = request('type', 1);
        $remark = request('remark');
        // 1增加，默认
        $money = request('money');
        $id = request('id');
        if (!$money || !$id) {
            return error('参数错误');
        }
        // $info  = CzChannel::find($id);
        DB::transaction(function () use ($type, $money, $id, $remark) {
            // 获取渠道订单中成功的订单总金额
            $channel_price = ChannelOrder::where('channel_id', $id)->where('channel_order_status', 3)->sum('channel_price');
            logger('price' . $channel_price);
            // 所有加款
            $all_add_money = ChannelMoneyLog::where('channel_id', $id)->where('type', 1)->sum('money');
            // 所有扣款
            $all_dec_money = ChannelMoneyLog::where('channel_id', $id)->where('type', 2)->sum('money');
            $before_money = -$channel_price;
            if ($all_add_money) {
                $before_money = $before_money + $all_add_money;
            }
            if ($all_dec_money) {
                $before_money = $before_money - $all_dec_money;
            }
            if ($type == 1) {
                $after_money = $before_money + $money;
            } else {
                $after_money = $before_money - $money;
            }
            if (!$remark) {
                $remark = "管理员" . ($type == 1 ? "增加" : '减少') . abs($money) . '元';
            }
            // 添加第三张表记录
            ChannelMoneyLog::create([
                "money" => $money,
                "type" => $type,
                "channel_id" => $id,
                "before_money" => $before_money,
                "after_money" => $after_money,
                "remark" => $remark
            ]);
            if ($type == 1) {
                // $info->increment('money', $money);
                CzChannel::where('id', $id)->increment('money', $money);
            } else {
                CzChannel::where('id', $id)->decrement('money', $money);
                // $info->decrement('money', $money);
            }
        });

        return success();
    }
    // 获取渠道预计余额
    public function lookChannelMoney(Request $request)
    {
        $id = request('id');
        $all_money = ChannelOrder::where('channel_id', $id)->where('channel_order_status', 3)->sum('channel_price');
        // 所有加款
        $all_add_money = ChannelMoneyLog::where('channel_id', $id)->where('type', 1)->sum('money');
        // 所有扣款`
        $all_dec_money = ChannelMoneyLog::where('channel_id', $id)->where('type', 2)->sum('money');
        $res = number_format((-$all_money) + $all_add_money - $all_dec_money, 2);
        return success(['data' => $res]);
    }
    //获取渠道修改余额记录
    public function getChannelMoneyLogList(Request $request)
    {
        $id = request('id');
        if (!$id) {
            return error('参数错误');
        }
        $paginator = ChannelMoneyLog::with(['channel'])->filter($request->all())->where('channel_id', $id)->orderBy('id', 'desc')->paginate($this->pageSize);
        $channel_price = ChannelOrder::where('channel_id', $id)->where('channel_order_status', 3)->sum('channel_price');
        $data = page_format($paginator);
        $data['all_money'] = $channel_price;
        return success($data);
    }
    public function index(Request $request)
    {
        // CzOrder::where('channle_id',)
        $created_at = request('params');
        // dd($created_at);
        $start_time = 0;
        $end_time = 0;
        if ($created_at) {
            $start_time = strtotime($created_at['beginTime']);
            $end_time = strtotime($created_at['endTime']);
        }
        // 获取渠道的余额
        // $paginator = CzChannel::filter($request->all())->withCount([
        //     'channel_order as channel_order_count' => function ($q) use ($start_time, $end_time) {
        //         if ($start_time && $end_time) {
        //             $q->whereBetween('created_at', [$start_time, $end_time]);
        //         }
        //         $q->where('channel_order_status', 3)->select(DB::raw("sum(channel_price) as price_sum"));
        //     }
        // ])->orderBy('id', 'desc')->paginate($this->pageSize);
        $paginator = CzChannel::filter($request->all())->orderBy('id', 'desc')->paginate($this->pageSize);

        return success(page_format($paginator));
    }

    public function listAll()
    {
        $items = CzChannel::all();
        return success(['data' => $items]);
    }

    public function show(Request $request, CzChannel $model)
    {
        $id = $request->get('id');
        $data = $model->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function create(CzChannelRequest $request)
    {
        $params = $request->all();
        $model = CzChannel::create($params);
        return success([], '添加成功');
    }

    public function update(CzChannelRequest $request, CzChannel $model)
    {
        $id = $request->post('id');
        $dept = $model->find($id);
        if ($dept) {
            $dept->update($request->all());
        } else {
            return error('数据不存在');
        }

        return success([], '更新成功');
    }

    public function destroy($ids, Request $request, CzChannel $model)
    {
        $id_arr = explode(',', $ids);
        DB::transaction(function () use ($id_arr, $model) {
            $model->destroy($id_arr);
            DB::table('cz_channel_product')->whereIn('channel_id', $id_arr)->delete();
            //删除客户以及分组的渠道分配
            DB::table('cz_customer_product_channel')->whereIn('channel_id', $id_arr)->delete();
            DB::table('cz_user_group_product_channel')->whereIn('channel_id', $id_arr)->delete();
        });
    }

    public function syncUpBalance(Request $request)
    {
        $ids = request('ids', null);
        if (!$ids) {
            return error('ids is required');
        }
        foreach ($ids as $id) {
            $channel = CzChannel::find($id);
            if (!$channel) {
                // 渠道不存在
                $channel->msg = 'id查询渠道不存在';
                $channel->save();
                continue;
            }
            $channel_file = base_path('channel/template/') . "{$channel->channel_code}.php";
            if (!file_exists($channel_file)) {
                // 渠道文件不存在
                $channel->msg = '服务器渠道文件不存在';
                $channel->save();
                continue;
            }
            $setting_arr = $channel->setting;
            $setting = [];
            foreach ($setting_arr as $v) {
                $setting[$v['name']] = $v['val'];
            }
            $setting['channel_code'] = $channel->channel_code;
            $setting['channel_id'] = $id;
            $setting['callback_url'] = $channel->callback_url;
            include_once $channel_file;
            $obj = new $channel['channel_code']($setting);
            if (method_exists($obj, 'queryBalance')) {
                $res = $obj->queryBalance();
                if ($res['code'] == 200) {
                    $channel->balance = $res['balance'];
                    $channel->credit = $res['credit'];
                    $channel->msg = '查询成功,查询时间' . date("Y-m-d H:i:s");
                    $channel->backParams = json_encode($res);

                    $channel->save();
                } else {
                    $channel->msg = '查询失败:' . $res['msg'];
                    $channel->backParams = json_encode($res);
                    $channel->save();
                }
            } else {
                $channel->msg = '上游不支持查询余额';
                $channel->save();
            }
        }
        return success();
    }
    // 同步渠道余额
    public function getTemplateList(Request $request)
    {
        $setting_file = base_path('channel/') . "list.php";
        if (!is_file($setting_file)) {
            return error('配置文件不存在');
        }
        $data = require_once($setting_file);

        return success(['data' => $data['list']]);
    }
    public function productList(Request $request)
    {
        $paginator = ChannelProduct::with(['product', 'channel', 'spec'])->filter($request->all())->paginate($this->pageSize);
        return success(page_format($paginator));
    }

    public function listAllChannelProduct()
    {
        $items = ChannelProduct::with([
            'product' => function ($query) {
                $query->select('id', 'title');
            },
            'channel' => function ($query) {
                $query->select('id', 'channel_name');
            },
            'spec' => function ($query) {
                $query->select('id', 'face_value');
            },
        ])->orderBy('channel_id', 'desc')->get();
        return success(['data' => $items]);
    }

    public function addProduct(ChannelProductRequest $request)
    {
        $params = $request->all();
        DB::transaction(function () use ($params) {
            $items = $params['items'];
            if (count($items) > 0) {
                foreach ($items as $item) {
                    $tmp_add = [
                        'product_id' => intval($item['product_id']),
                        'spec_id' => intval($item['spec_id']),
                        'channel_id' => intval($item['channel_id']),
                        'channel_api_code' => trim($item['channel_api_code']),
                        'channel_price' => floatval($item['channel_price']),
                    ];
                    ChannelProduct::updateOrCreate(
                        [
                            'spec_id' => intval($item['spec_id']),
                            'channel_id' => intval($item['channel_id']),
                        ],
                        [
                            'product_id' => intval($item['product_id']),
                            'channel_api_code' => trim($item['channel_api_code']),
                            'channel_price' => floatval($item['channel_price']),
                        ]
                    );
                }
            }
        });
        return success([], '添加成功');
        /*
        $params = $request->all();
        $items = $params['items'];
        $model = ChannelProduct::upsert($items,['spec_id', 'channel_id'],['channel_api_code', 'channel_price']);
        return success([],'更新成功');
        */
    }

    public function getProduct(Request $request, ChannelProduct $model)
    {
        $id = $request->get('id');
        $data = $model->with(['product', 'channel', 'spec'])->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function updateProduct(Request $request, ChannelProduct $model)
    {
        $id = $request->post('id');
        $data = $model->find($id);
        if ($data) {
            $data->update($request->only(['channel_api_code', 'channel_price']));
        } else {
            return error('数据不存在');
        }

        return success([], '更新成功');
    }

    public function destroyProduct($ids, Request $request, ChannelProduct $model)
    {
        $id_arr = explode(',', $ids);
        $model->destroy($id_arr);
    }

    public function setPrice(Request $request)
    {
        $params = $request->all();
        DB::transaction(function () use ($params) {
            $items = $params['items'];
            if (count($items) > 0) {
                foreach ($items as $item) {
                    $tmp_add = [
                        'product_id' => intval($item['product_id']),
                        'spec_id' => intval($item['spec_id']),
                        'channel_id' => intval($item['channel_id']),
                        'channel_price' => floatval($item['channel_price']),
                    ];
                    $model = ChannelProduct::where('spec_id', intval($item['spec_id']))->where('channel_id', intval($item['channel_id']))->first();
                    $model->update([
                        'channel_price' => floatval($item['channel_price']),
                    ]);
                }
            }
        });
        return success([], '添加成功');
    }

    public function groupList(Request $request)
    {
        $paginator = ChannelGroup::with(['items', 'items.channel'])->filter($request->all())->orderBy('id', 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }
    public function listAllGroup(Request $request)
    {
        $items = ChannelGroup::all();
        if ($items) {
            $items = $items->toArray();
            array_unshift($items, [
                'id' => 0,
                'title' => '非渠道组'
            ]);
        }
        return success(['data' => $items]);
    }

    public function addGroup(ChannelGroupRequest $request)
    {
        $params = $request->all();
        DB::transaction(function () use ($params) {
            if (isset($params['id']) && $params['id'] > 0) {
                $model = ChannelGroup::find($params['id']);
                $model->update([
                    'title' => $params['title'],
                    'sort_type' => $params['sort_type'],
                ]);
            } else {
                $model = ChannelGroup::create($params);
            }
            ChannelGroupItem::where('channel_group_id', $model->id)->delete();
            $items = $params['channels'];
            foreach ($items as $item) {
                $add_datas[] = [
                    'channel_id' => $item['channel_id'],
                    'channel_group_id' => $model->id,
                    'submit_nums' => $item['submit_nums'] ?? 1,
                    'sort' => $item['sort'] ?? 1,
                ];
            }

            ChannelGroupItem::upsert($add_datas, ['channel_id', 'channel_group_id'], ['submit_nums', 'sort']);
        });
        return success([], '添加成功');
    }

    public function updateGroup()
    {
    }
    public function getGroup(Request $request, ChannelGroup $model)
    {
        $id = $request->get('id');
        $data = $model->with(['items', 'items.channel'])->find($id);
        return success(['data' => $data->toArray(), 'check_ids' => $data->items->pluck('channel_id')]);
    }
    public function delGroup($ids, Request $request, ChannelGroup $model)
    {
        $id_arr = explode(',', $ids);
        DB::transaction(function () use ($id_arr, $model) {
            $model->destroy($id_arr);
            //删除客户以及分组的渠道组分配
            DB::table('cz_customer_product')->whereIn('channel_group_id', $id_arr)->delete();
            DB::table('cz_user_group_product')->whereIn('channel_group_id', $id_arr)->delete();
        });
    }
}
